package com.cherrish.demo.protocol.dubbo;

import com.cherrish.demo.framework.Invocation;
import com.cherrish.demo.framework.URL;
import com.cherrish.demo.register.Register;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;
import java.net.InetSocketAddress;

/**
 * @author cherrish
 * @time 2019-03-20 17:14
 * @name NettyServerHandler
 * @desc:
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Invocation invocation = (Invocation) msg;
        InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().localAddress();
        Class serviceImpl = Register.get(new URL(inetSocketAddress.getHostName(), inetSocketAddress.getPort()), invocation.getInterfaceName());
        Method method = serviceImpl.getMethod(invocation.getMethodName(), invocation.getParamTypes());
        Object result = method.invoke(serviceImpl.newInstance(), invocation.getParams());
        System.out.println("Netty----------------->" + result.toString());
        ctx.writeAndFlush("Netty: " + result);
    }
}
